<?php


namespace app\msgapi\service;

use think\{App, Model, Request};
use app\msgapi\model\{BaseModel, AuthGroup, AuthRule};
use app\utils\Arr;
error_reporting(E_ERROR | E_PARSE);
class BaseService
{
    protected App $app;
    protected Request $request;
    protected BaseModel $model;

    public function __construct()
    {
        $this->app = app();
        $this->request = $this->app->request;
//        $this->authRule = $this->app->make(AuthRule::class);// 创建实例，会放在app中
//        $this->authGroup = $this->app->make(AuthGroup::class);
    }

    // 公共模板方法
    public function getLists()
    {
        $data = input('param.');    $limit = input('limit');
        $data['nid'] && $where[] = ['nid','=',$data['nid']];
        $data['title'] && $where[] = ['title_cn','like',"%{$data['title']}%"];
        $order = 'sort desc,add_time desc';
        if ($data['order']) {
            $order = $data['order'].' '.($data['sort']?:'desc');
        }

        $list = $this->model->where($where)->order($order)->paginate($limit)->toArray();
        $list['code'] = 0;// 用于前台数据表格判断成功字段
        return $list;
    }
    public function getRows($id)
    {
        $rows = $this->model->findOrEmpty($id)->toArray();
        return success_json('成功',$rows);
    }
    public function _save()
    {
        $data = input('post.');
        if($check = $this->model->validate($data)){
            return error_json($check);
        }
        // 图集排序
        Arr::arrayToSort($data['json_cn']);
        Arr::arrayToSort($data['json_en']);
        try{
            $data['id']?$this->model::update($data):$this->model::create($data);
            return success_json('保存成功');
        } catch (\Exception $e){
            return error_json('保存失败，请重试');
        }
    }
    public function setStatus()
    {
        $this->model->allowField(['state','sort'])->update(input('post.'),['id'=>input('id/d')]);
        return success_json('更新成功');
    }
    public function _delete($id, bool $force = false)
    {
        if(!$id){
            return error_json('请选择需要删除的信息');
        }
        $res = $this->model::destroy($id, $force);  // 返回bool
        if($res){
            return success_json('删除成功');
        }else{
            return error_json('删除失败，请重试');
        }
    }
    /**
     * 处理数据集数组，使之能够对数组表单赋值（由于layui2.5.7的form.val不能赋值数组字段，请跟进后续layui更新）
     * @param Model $collection
     * @return array
     */
    protected function arrayVal(Model $collection)
    {
        $arr = $collection->toArray();
        foreach ($arr as $k => $v) {
            if (!is_array($v)) {
                continue;
            }
            foreach ($v as $k1 => $v1) {
                if(!is_array($v1)){
                    $arr[$k . '[' . $k1 . ']'] = $v1;
                }
                foreach ($v1 as $k2 => $v2){
                    $arr[$k . '[' . $k1 . ']' . '[' . $k2 . ']'] = $v2;
                }
            }
        }
        return $arr;
    }

}